package com.azure.code.slidingwindow;

import java.util.HashMap;
import java.util.Map;

/**
 * 无重复字符最长子串
 * 给定一个字符串s，请找出其中不含有重复字符的 最长子串长度
 * <p>
 * 输入 s="abcabcbb"
 * 输出 3
 */
public class LengthOfLongestSubstring_3 {

    public int lengthOfLongestSubtring(String s) {
        Map<Character, Integer> window = new HashMap<>();

        int left = 0, right = 0;
        int res = 0;
        while (right < s.length()) {
            char c = s.charAt(right);
            right++;
            // 进行窗口内数据一些列更新
            window.put(c, window.getOrDefault(c, 0) + 1);

            // 判断左侧窗口是否要收缩
            while (window.get(c) > 1) {
                char d = s.charAt(left);
                left++;
                // 进行窗口内数据一些列更新
                window.put(d, window.getOrDefault(d, 0) - 1);
            }
            res = Math.max(res, right - left);
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(new LengthOfLongestSubstring_3().lengthOfLongestSubtring("abcabcbb"));
    }
}
